`<script setup>
import {reactive, ref} from "vue";
import request from "@/utils/request";
import {ElMessage} from "element-plus";
import router from "@/router";
import useUserInfoStore from '@/stores/userInfo.js'
import {useTokenStore} from '@/stores/token.js'

const userInfoStore = useUserInfoStore()
const tokenStore = useTokenStore()

const formData = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 验证密码复杂性
const validatePassword = (password) => {
  return password.length >= 5 && password.length <= 16;
};

// 保存密码
const save = async () => {
  const {oldPassword, newPassword, confirmPassword} = formData;

  // 验证逻辑
  if (!oldPassword) {
    ElMessage.error("请输入原密码");
    return;
  }
  if (!newPassword) {
    ElMessage.error("请输入新密码");
    return;
  }
  if (!confirmPassword) {
    ElMessage.error("请输入确认新密码");
    return;
  }
  if (newPassword !== confirmPassword) {
    ElMessage.error("确认新密码错误");
    return;
  }
  if (!validatePassword(newPassword)) {
    ElMessage.error("密码长度为5~16位非空字符");
    return;
  }

  try {
    // 使用JSON格式发送数据
    const result = await request.put("/users/password", JSON.stringify({
      oldPassword,
      newPassword,
      confirmPassword
    }), {
      headers: {
        'Content-Type': 'application/json'
      }
    });

    if (result.code === 200) {
      ElMessage.success("修改密码成功");
      // 清除token和用户信息
      tokenStore.removeToken();
      userInfoStore.removeInfo();
      // 跳转到登录页
      router.push("/login");
    } else {
      ElMessage.error(result.msg || "修改密码失败");
    }
  } catch (error) {
    console.error('Password update error:', error);
    ElMessage.error(error.response?.data?.msg || "修改密码失败");
  }
};
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>修改密码</span>
      </div>
    </template>

    <el-form :model="formData" label-width="120px">
      <el-form-item label="原密码" prop="oldPassword">
        <el-input v-model="formData.oldPassword" type="password" show-password placeholder="请输入原密码"/>
      </el-form-item>

      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="formData.newPassword" type="password" show-password placeholder="请输入新密码"/>
      </el-form-item>

      <el-form-item label="确认新密码" prop="confirmPassword">
        <el-input v-model="formData.confirmPassword" type="password" show-password placeholder="请再次输入新密码"/>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="save">保存修改</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  :deep(.el-form) {
    max-width: 500px;
    margin: 0 auto;
  }
}
</style>`